package jju.edu.mvptest;

import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import jju.edu.mvptest.model.Phone;
import jju.edu.mvptest.presenter.PhonePresenter;
import jju.edu.mvptest.presenter.TaskPresenter;
import jju.edu.mvptest.view.OperationView;

public class MainActivity extends AppCompatActivity implements OperationView{

    private ListView listView;
    private Button btnCreate;
    private TaskPresenter phonePresenter;
    private ProgressDialog mLoadingDialog;
    private ArrayAdapter<Phone> mAdapter;
    private Toast toast;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView)findViewById(R.id.phone_list);
        btnCreate = (Button) findViewById(R.id.button);
        phonePresenter = new PhonePresenter(this);
        mAdapter = new ArrayAdapter<Phone>(MainActivity.this, android.R.layout.simple_list_item_1,phonePresenter.getPhonesList());
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> view, View view1, int i, long l) {
                phonePresenter.removePhone(i);
            }
        });
        btnCreate.setOnClickListener(listener);

    }
    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            phonePresenter.addRandomPhone();
        }
    };
    @Override
    public void showCreatingPhone() {
        mLoadingDialog = new ProgressDialog(this);
        mLoadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mLoadingDialog.setMessage("工厂正在生产手机");
        mLoadingDialog.setCancelable(true);
        mLoadingDialog.show();
    }

    @Override
    public void showPhoneCountChange() {
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void showNoPhone() {
    }

    @Override
    public void showFactoryBusy() {
        showToast("工厂繁忙，请稍后再试！");
    }

    @Override
    public void showCreatedPhone() {
            if(mLoadingDialog!=null && mLoadingDialog.isShowing()){
                mLoadingDialog.dismiss();
            }
            mLoadingDialog = null;
        showToast("新生产出一台手机！");
    }

    public void showToast(String str){
        if(toast == null){
            toast = Toast.makeText(MainActivity.this,str,Toast.LENGTH_SHORT);
        }else{
            toast.setText(str);
        }
        toast.show();
    }

}
